package com.ficus.road.maintain.handler.smartdecision.handlers.highway;

import com.ficus.road.maintain.core.model.smartnew.SmartDecisionExcelVO;
import com.ficus.road.maintain.core.model.smartnew.SmartDecisionHighwayRequest;
import com.ficus.road.maintain.core.model.smartnew.SmartDecisionResponse;
import com.ficus.road.maintain.dao.smartnew.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author xiawen yang
 * @date 2022/7/20 下午3:51
 */
@Component
@RequiredArgsConstructor
public class SmartDecisionHandlerChainStarter {

    private final List<AbstractSmartDecisionHighwayHandler> abstractSmartDecisionHighwayHandlerList;
    private final SmartHighwayDao smartHighwayDao;
    private final SmartTableMergedDao smartTableMergedDao;
    private final SmartTableUnmergedDao smartTableUnmergedDao;
    private final SmartValuationMergedDao smartValuationMergedDao;
    private final SmartValuationUnmergedDao smartValuationUnmergedDao;
    private final SmartDecisionResponseDao smartDecisionResponseDao;
    private AbstractSmartDecisionHighwayHandler firstHandlerOfSmartDecisionChain;

    @PostConstruct
    void initChainHandler() {
        for (int i = 0; i < abstractSmartDecisionHighwayHandlerList.size(); i++) {
            if (i == 0) {
                firstHandlerOfSmartDecisionChain = abstractSmartDecisionHighwayHandlerList.get(0);
            } else {
                AbstractSmartDecisionHighwayHandler currentHandler = abstractSmartDecisionHighwayHandlerList.get(i - 1);
                AbstractSmartDecisionHighwayHandler nextHandler = abstractSmartDecisionHighwayHandlerList.get(i);
                currentHandler.setNextHighwayHandler(nextHandler);
            }
        }
    }

    public void start() {
        preProcess();
        firstHandlerOfSmartDecisionChain.handle(buildRequest(), SmartDecisionResponse.ofAllResponse());
    }

    /**
     * 前置处理, 暂时把之前的基础路段数据和计算结果删除
     */
    private void preProcess() {
        smartTableMergedDao.deleteAll();
        smartTableUnmergedDao.deleteAll();
        smartValuationMergedDao.deleteAll();
        smartValuationUnmergedDao.deleteAll();
        smartDecisionResponseDao.deleteAll();
    }

    private SmartDecisionHighwayRequest buildRequest() {
        List<SmartDecisionExcelVO> params = smartHighwayDao.findAll();
        SmartDecisionHighwayRequest request = SmartDecisionHighwayRequest.builder().params(params).build();
        return request;
    }
}
